package com.upb.webserver.chainhost;

import com.upb.webserver.chain.ChainManager;
import com.upb.webserver.chain.ChainService;
import com.upb.webserver.common.tools.MybatisExampleTools;
import com.upb.webserver.dao.entity.TbChain;
import com.upb.webserver.dao.entity.TbChainHost;
import com.upb.webserver.dao.entity.TbChainHostExample;
import com.upb.webserver.dao.entity.TbHost;
import com.upb.webserver.dao.mapper.TbChainHostMapper;
import com.upb.webserver.host.HostManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Slf4j
@Service
public class ChainHostService {
    @Autowired
    private TbChainHostMapper chainHostMapper;
    @Autowired
    private ChainManager chainManager;
    @Autowired
    private HostManager hostManager;


    /**
     * @param chainId
     * @param hostId
     * @param nodeCount
     */
    @Transactional
    public void saveChainHost(Integer chainId, Integer hostId, Integer nodeCount) {
        log.info("start exec method [saveChainHost]. chainId:{} hostId:{} nodeCount:{}", hostId, hostId, nodeCount);

        //check chainId
        TbChain tbChain = chainManager.verifyChainId(chainId);
        //check hostId
        TbHost tbHost = hostManager.verifyHostId(hostId);

        //check chain-host
        TbChainHostExample example = MybatisExampleTools.initSampleExample(TbChainHostExample.class, new TbChainHost(chainId, hostId));
        if (chainHostMapper.countByExample(example) > 0) {
            log.info("finish exec method [saveChainHost].  found record by chainId:{} hostId:{} ", hostId, hostId);
            return;
        }

        //save chain-org
        TbChainHost tbChainHost = new TbChainHost();
        tbChainHost.setChainId(chainId);
        tbChainHost.setCompanyId(tbHost.getCompanyId());
        tbChainHost.setNodeCount(nodeCount);
        tbChainHost.setHostId(hostId);
        tbChainHost.setChainType(tbChain.getChainType());
        tbChainHost.setGmtCreate(new Date());
        tbChainHost.setGmtModified(new Date());

        chainHostMapper.insert(tbChainHost);
        log.info("success exec method [saveChainOrg]. ");
    }


}
